<?php

App::uses('AppModel', 'Model');

class Taste extends AppModel {
    
    public $belongsTo = array('TasteGroup');
    
    public $order = 'Taste.name';
    
    public function beforeSave($options=array()) {
        if ($upload = $this->getImageForUpload()) {
            $data = $this->data['Taste'];
            if (! empty($data['image'])) {
                $this->deleteImage($data['image']);
            }
            
            $data['image'] = $upload['name'];
            $this->set($data);
        }
        
        return parent::beforeSave($options);
    }
    
    public function afterSave($created, $options=array()) {
        if ($upload = $this->getImageForUpload()) {
            $dest = IMG_DIR . implode(DS, array('ukusi', $upload['name']));
            @move_uploaded_file($upload['tmp_name'], $dest);
        }
        
        return parent::afterSave($created, $options);
    }
    
    public function beforeDelete($cascade = true) {
        $this->prevData = $this->findById($this->id);
        return parent::beforeDelete($cascade);
    }
    
    public function afterDelete() {
        $data = $this->prevData['Taste'];
        if (! empty($data['image'])) {
            $this->deleteImage($data['image']);
        }
        
        return parent::afterDelete();
    }
    
    public function getAll($fields = array('Taste.id', 'Taste.name', 'Taste.image')) {
        $ret = array();
        
        $fields[] = 'TasteGroup.name';
        
        foreach ( $this->find('all', array(
            'fields' => $fields,
            'recursive' => 0
        )) as $row) {
            $groupName = $row['TasteGroup']['name'];
            if (empty($ret[$groupName])) {
                $ret[$groupName] = array();
            }
            $ret[$groupName][] = $row;
        }
        
        return $ret;
    }
    
    private function getImageForUpload() {
        $ret = false;
        $data   = $this->data['Taste'];
        $upload = $data['image_upload'];
        if (! $upload['error']) {
            $ret = $upload;
        }
    
        return $ret;
    }
    
    private function deleteImage($image) {
        @unlink(IMG_DIR . 'ukusi' . DS . $image);
    }
    
}